import javax.lang.model.util.SimpleAnnotationValueVisitor6;
import java.util.*;

/**
 * @Author: Liu, Yunfeng
 * @DateTime: 2021/7/25 21:30
 * @Description: TODO
 */
public class adjacentPairs {
    public static int[] restoreArray(int[][] adjacentPairs) {
        int length = adjacentPairs.length + 1;
        Map<Integer, List<Integer>> map = new HashMap(2 * length);
        for (int i = 0; i < adjacentPairs.length; i++) {
            map.putIfAbsent(adjacentPairs[i][0], new ArrayList<>());
            map.putIfAbsent(adjacentPairs[i][1], new ArrayList<>());
            map.get(adjacentPairs[i][0]).add(adjacentPairs[i][1]);
            map.get(adjacentPairs[i][1]).add(adjacentPairs[i][0]);
        }
        int[] result = new int[length];
        for(int key : map.keySet()){
            if(map.get(key).size() == 1){
                result[0] = key;
                break;
            }
        }
        result[1] = map.get(result[0]).get(0);
        for (int i = 1; i < length-1; i++) {
            List<Integer> list = map.get(result[i]);
            result[i+1] = result[i-1] == list.get(0)?list.get(1):list.get(0);
        }
        return result;
    }

    public static void main(String[] args) {
        int[][] adjacentPairs = {{4,-2},{1,4},{-3,1}};
        int[] list = restoreArray(adjacentPairs);
        Arrays.stream(list).forEach(i -> {
                    System.out.print(i + " ");
                }
        );
    }
}
